<template>
  <div class="embed-page-container" v-loading="loading"></div>
</template>
<script>
import {
  tokenRefresh,
  getTenantByUid,
  getPermissionByUserIdAndTenant,
} from "@/api/auth";
import { getNodeByKey } from "@/utils";
export default {
  data() {
    return {
      loading: true,
    };
  },
  mounted() {
    let isIframe = window.self !== window.top;
    if (!isIframe) {
      let token = localStorage.getItem("ACCESS_TOKEN");
      let loginPage = localStorage.getItem("loginPage");
      this.$router.replace({
        path: token ? `/` : "/common/login",
      });
      return;
    }
    this.initPage();
  },
  methods: {
    //初始化
    initPage() {
      let { id } = this.$route.query;
      if (!id) {
        this.$message.error("您无权访问");
        this.loading = false;
        return;
      }
      localStorage.setItem("EMBED_SOURCE", JSON.stringify(this.$route.query));
      this.getAuthorization(id);
    },

    //查询鉴权信息
    getAuthorization(id) {
      return new Promise((resolve, reject) => {
        tokenRefresh({ userId: id })
          .then((res) => {
            let { data } = res;
            let { access_token, userInfo } = data;
            localStorage.setItem("LOGIN_DATA", JSON.stringify(data));
            localStorage.setItem("ACCESS_TOKEN", access_token);
            localStorage.setItem("USER_INFO", JSON.stringify(userInfo));
            localStorage.setItem("USER_ID", userInfo.uid);
            this.getTenantData();
            resolve();
          })
          .catch((_) => {
            this.loading = false;
            this.$message.error("授权失败，请稍后重试");
            reject();
          })
          .finally((_) => {});
      });
    },

    //查询租户列表
    getTenantData() {
      let { id, tCode } = this.$route.query;
      return new Promise((resolve, reject) => {
        getTenantByUid({ userId: id })
          .then((res) => {
            let { data } = res;
            let source = data?.result || [];
            let org = getNodeByKey(tCode, "tenantCode", source, "child");
            if (org) {
              localStorage.setItem("ORGANIZATION", JSON.stringify(org));
              this.$store.dispatch("setStoreState", {
                ORGANIZATION: org,
              });
              this.getMenuSource();
            } else {
              this.loading = false;
              this.$message.error("租户信息获取失败，请稍后重试");
            }
            resolve();
          })
          .catch((_) => {
            this.loading = false;
            this.$message.error("租户信息获取失败，请稍后重试");
            reject();
          })
          .finally((_) => {});
      });
    },

    //查询权限菜单数据
    getMenuSource() {
      let { id, tCode, mCode, sSource, single } = this.$route.query;
      return new Promise((resolve, reject) => {
        getPermissionByUserIdAndTenant({ userId: id, tenantCode: tCode })
          .then((res) => {
            let { data } = res;
            let source = data?.result || [];
            source.forEach((v) => {
              v.childs = v.child;
            });
            let itemMenu = getNodeByKey(mCode, "menuCode", source, "childs");
            let itemSystem = getNodeByKey(
              sSource,
              "menuCode",
              source,
              "childs"
            );
            this.$store.dispatch("setStoreState", {
              CURRENT_MENU: itemMenu,
            });
            localStorage.setItem("CURRENT_MENU", JSON.stringify(itemMenu));
            //
            this.$store.dispatch("setStoreState", {
              SYSTEM: itemSystem,
            });
            localStorage.setItem("SYSTEM", JSON.stringify(itemSystem));
            //
            this.$store.dispatch("setStoreState", {
              PERMISIONS_DATA: source,
            });
            //
            this.$router.replace({
              path: `/?single=${single || ""}`,
              query: {
                embed: true,
              },
            });
            resolve();
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },
  },
};
</script>
<style lang="less" scoped>
.embed-page-container {
  width: 100%;
  height: 100%;
  background: transparent;
}
</style>
